package com.lutzyt.delivery.config.handler;

import com.lutzyt.delivery.exception.BusinessException;
import com.lutzyt.delivery.util.Result;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Author: zyt
 */
@ControllerAdvice
public class ControllerExceptionHandler {

  /**
   * 处理系统发生的任意错误时的处理
   *
   * @param e
   * @return
   */
  @ResponseBody
  @ExceptionHandler(Throwable.class)
  public Result error(Exception e) {
    e.printStackTrace();
    return Result.fail(e.getMessage());
  }

  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseBody
  public Result methodArgumentNotValidException(MethodArgumentNotValidException c) {
    List<ObjectError> errors = c.getBindingResult().getAllErrors();
    StringBuffer errorMsg = new StringBuffer();
    errors.forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));
    return Result.fail(errorMsg.toString());
  }

  @ExceptionHandler(BusinessException.class)
  @ResponseBody
  public Result<Void> businessException(BusinessException c) {
    return c.toResult();
  }

}
